package com.telecom.restaurant.service;

import com.telecom.restaurant.constant.DataResultConstant;
import com.telecom.restaurant.constant.DefaultConstant;
import com.telecom.restaurant.dao.MenuDayToFoodDao;
import com.telecom.restaurant.dao.UserCartDao;
import com.telecom.restaurant.domin.DataResult;
import com.telecom.restaurant.domin.vo.CartFoodVO;
import com.telecom.restaurant.enums.FoodTypeEnum;
import com.telecom.restaurant.exception.BizException;
import com.telecom.restaurant.model.FoodPO;
import com.telecom.restaurant.model.MenuDayToFoodPO;
import com.telecom.restaurant.model.UserCartPO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.telecom.restaurant.constant.DefaultConstant.PACKAGE_FOOD_PRICE;
import static com.telecom.restaurant.enums.FoodTypeEnum.*;

/**
 * Created by qiqi on 2019/12/22.
 */
@Service
public class CartService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserCartDao userCartDao;

    @Autowired
    private FoodService foodService;

    @Autowired
    private MenuDayToFoodDao menuDayToFoodDao;

    @Autowired
    private PictureService pictureService;


    public CartFoodVO addCart(String menuFoodIds, Integer count, Long userId) throws BizException {
        String[] menuFoodArray = menuFoodIds.split(",");
        int type = ORDER_OTHER_FOOD.getCode();
        if (menuFoodArray.length == 5) {
            // 四个菜+主食
            type = ORDER_PACKAGE_FOOD.getCode();
        }

        List<Long> menuFoodIdList = new ArrayList<>(menuFoodArray.length);
        for (String stringId : menuFoodArray) {
            menuFoodIdList.add(Long.valueOf(stringId));
        }
        List<MenuDayToFoodPO> menuFoodPOList = menuDayToFoodDao.selectByIds(menuFoodIdList);
        if (menuFoodPOList == null || menuFoodPOList.isEmpty()) {
            return null;
        }

        UserCartPO userCartPO = new UserCartPO();
        userCartPO.setUserId(userId);
        userCartPO.setCount(count);
        userCartPO.setMenuFoodIds(menuFoodIds);
        if (type == ORDER_PACKAGE_FOOD.getCode()) {
            // 如果是套餐
            userCartPO.setPicture(DefaultConstant.PACKAGE_FOOD_PICTURE);
            userCartPO.setMenuFoodIds(menuFoodIds);
            userCartPO.setPrice(PACKAGE_FOOD_PRICE);
            userCartPO.setType(ORDER_PACKAGE_FOOD.getCode());
            StringBuilder nameBuilder = new StringBuilder();
            for (MenuDayToFoodPO menuFoodPO : menuFoodPOList) {
                FoodPO food = foodService.getFoodById(menuFoodPO.getFoodId());
                if (food.getType() != PACKAGE_DISH.getCode() && food.getType() != PACKAGE_MAIN.getCode()) {
                    throw new BizException(DataResultConstant.CHOOSE_FOOD_WRONG);
                }
                // 检查库存
                if (menuFoodPO.getCount() < count) {
                    throw new BizException(new DataResult(DataResultConstant.FOOD_STOCK_NOT_ENOUGH.getCode(),
                            "【" + food.getName() + "】" + DataResultConstant.FOOD_STOCK_NOT_ENOUGH.getMsg()));
                }
                if (food != null) {
                    if (nameBuilder.length() > 0) {
                        nameBuilder.append("，");
                    }
                    nameBuilder.append(food.getName());
                }
            }
            userCartPO.setName(nameBuilder.toString());
        } else {
            // 小吃
            FoodPO food = foodService.getFoodById(menuFoodPOList.get(0).getFoodId());
            if (food == null) {
                throw new BizException(DataResultConstant.CHOOSE_FOOD_WRONG);
            }
            if (food.getType() != OTHER_DISH.getCode() && food.getType() != OTHER_MAIN.getCode()) {
                throw new BizException(DataResultConstant.CHOOSE_FOOD_WRONG);
            }
            // 检查库存
            if (menuFoodPOList.get(0).getCount() < count) {
                throw new BizException(new DataResult(DataResultConstant.FOOD_STOCK_NOT_ENOUGH.getCode(),
                        "【" + food.getName() + "】" + DataResultConstant.FOOD_STOCK_NOT_ENOUGH.getMsg()));
            }
            userCartPO.setPicture(food.getPicture());
            userCartPO.setPrice(food.getPrice());
            userCartPO.setName(food.getName());
            userCartPO.setType(ORDER_OTHER_FOOD.getCode());
        }

        userCartDao.insert(userCartPO);
        return this.convertPO2VO(userCartPO);
    }

    public int clearCart(Long userId) {
        int result = userCartDao.deleteByUser(userId);
        return result;

    }


    public CartFoodVO getCartFoodById(Long id) {
        UserCartPO po = userCartDao.selectById(id);
        CartFoodVO vo = this.convertPO2VO(po);
        return vo;
    }

    public List<CartFoodVO> getAllByUserId(Long userId) {
        List<UserCartPO> poList = userCartDao.selectByUserId(userId);
        return convertVOList(poList);
    }

    public List<CartFoodVO> convertVOList(List<UserCartPO> poList) {
        if (CollectionUtils.isEmpty(poList)) {
            return Collections.emptyList();
        }
        List<CartFoodVO> voList = new ArrayList<>(poList.size());
        for (UserCartPO po : poList) {
            CartFoodVO vo = this.convertPO2VO(po);
            voList.add(vo);
        }
        return voList;
    }


    private CartFoodVO convertPO2VO(UserCartPO po) {
        if (po == null) {
            return null;
        }
        CartFoodVO vo = new CartFoodVO();
        vo.setCartFoodId(po.getId());
        vo.setPicture(po.getPicture());
        vo.setCount(po.getCount());
        vo.setName(po.getName());
        if (po.getType() == FoodTypeEnum.ORDER_PACKAGE_FOOD.getCode()) {
            vo.setPrice(PACKAGE_FOOD_PRICE);
            vo.setTotal(PACKAGE_FOOD_PRICE * po.getCount());
        } else {
            vo.setPrice(po.getPrice());
            vo.setTotal(po.getPrice() * po.getCount());
        }

        vo.setType(po.getType());
        return vo;
    }
}
